package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.adapter.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.*;
import com.lzx.iteam.data.CRMOrderFilterSource;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.widget.RefreshableHelper;
import com.lzx.iteam.widget.RefreshableView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.baidu.location.b.g.S;
import static com.baidu.location.f.mC;


/**
 * Created by Megan on 16/7/27.
 * 公海主页面
 */
public class CRMLibraryActivity extends MyBaseActivity implements View.OnClickListener, View.OnTouchListener, AdapterView.OnItemClickListener, AbsListView.OnScrollListener, AdapterView.OnItemLongClickListener {

    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLlBack;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.title_iv_right)
    private ImageView mIvRight;
    @FindViewById(id = R.id.title_iv_right_left)
    private ImageView mIvRightLeft;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.rl_library_order_by)
    RelativeLayout mRlOrderBy;
    @FindViewById(id = R.id.tv_library_order_by)
    TextView mTvOrderBy;
    @FindViewById(id = R.id.iv_library_order_by)
    ImageView mIvOrderBy;
    @FindViewById(id = R.id.rl_library_filter_by)
    RelativeLayout mRlFilterBy;
    @FindViewById(id = R.id.tv_library_filter_by)
    TextView mTvFilterBy;
    @FindViewById(id = R.id.iv_library_filter_by)
    ImageView mIvFilterBy;
    @FindViewById(id = R.id.hsv_library_filter)
    HorizontalScrollView mHsvFilter;
    @FindViewById(id = R.id.ll_library_filter_msg)
    LinearLayout mLlFilterMsg;
    @FindViewById(id = R.id.v_hsv_library_filter_line)
    View vHsvLine;
    @FindViewById(id = R.id.ll_library_no_data)
    LinearLayout mLlNoData;
    @FindViewById(id = R.id.lv_library_list)
    ListView mLvList;
    @FindViewById(id = R.id.lv_library_order_by_list)
    ListView mLvOrderBy;
    @FindViewById(id = R.id.ll_library_filter)
    LinearLayout mLlFilter;
    @FindViewById(id = R.id.lv_library_filter_first)
    ListView mLvFirstFilter;
    @FindViewById(id = R.id.lv_library_filter_second)
    ListView mLvSecondFilter;
    @FindViewById(id = R.id.tv_library_filter_by_clear)
    TextView mTvFilterClear;
    @FindViewById(id = R.id.tv_library_filter_by_ok)
    TextView mTvFilterOk;
    @FindViewById(id = R.id.refreshable_view)
    RefreshableView mRefreshableView;
    @FindViewById(id = R.id.view_filter_lv_bottom)
    View mFilterBottom;
    private TextView mHeaderText;
    private LinearLayout mHeaderLayout;
    private ProgressBar mHeaderProgress;
    private TextView mFooterText;
    private LinearLayout mFooterLayout;
    private ProgressBar mFooterProgress;
    private Dialog mWaitDialog;


    private String mGroupId;
    boolean is_scrolling = false;   // 是否还在滚动
    private int pageIndex = 1;      // 加载的页数
    private int pageSize = 10;
    private int currentCount;
    private int mPosition;

    private ArrayList<CRMFilterFirstData> firstDatas = new ArrayList<CRMFilterFirstData>();
    private int mFirstSelectedPosition = 0;
    private CRMFilterAdapter mFilterFirstAdapter;
    private CRMFilterAdapter mFilterSecondAdapter;
    private CRMOrderAdapter mOrderAdapter;
    private CRMLibraryListAdapter mAdapter;
    private CRMChanceListAdapter mChanceAdapter;
    private CRMClientListAdapter mClientAdapter;
    private CloudDBOperation mCloudDBOperation;
    private AllDialogUtil mDialogUtil;
    private CRMOrderFilterSource mCRMOrderFilterSource;
    private int type;//公海:Constants.CRM_PUBLIC_CLUE 线索: Constants.CRM_PRIVATE_CLUE 机会:Constants.CRM_CHANCE

    private String mOrigin = "-1";//线索来源 -1不限, 0其他,1.广告,2.研讨会,3.搜索引擎,4.客户介绍
    private String mStatus = "-1";//跟进状态 -1不限, 0.未处理,1.已联系,2.关闭
    private String mActiveTime = "-1";//活动记录 -1.不限, 0.最近7天,1.最近1月,2.最近3月,3.最近1年
    private String mUpdateTime = "-1";//修改日期 -1.不限, 0.最近7天,1.最近1月,2.最近3月,3.最近1年
    private String mCreateTime = "-1";//创建日期 -1.不限, 0.最近7天,1.最近1月,2.最近3月,3.最近1年
    private String mMarketStage = "-1";//销售阶段-1不限, 1.初步接洽、2.需求确定、3.方案报价、4.谈判审核、5.赢单、6.输单
    private String mMarketAmount = "-1";//销售金额-1.不限, 其他则数字表示,如 千:1000, 万:10000, ..
    private String mStatementDate = "-1";//结单日期 -1.不限, 0.本周,1.本月,2.本季度,3.本年,4.本日,5.下周,6.下月
    private int sort = 0;
    //排序, 0.创建时间,1.活动时间
    //排序 0.销售阶段,1.最高销售额,2.活动时间,3.更新时间

    private static final int MSG_GET_PUBLIC_LIST = 1000;
    private static final int MSG_GET_PUBLIC_DEL = 1001;
    private static final int MSG_GET_CHANCE_LIST = 1002;
    private ArrayList<CRMLibraryListData> crmLibraryListDatas = new ArrayList<CRMLibraryListData>();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_GET_PUBLIC_LIST:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0) {
                        ArrayList<CRMLibraryListData> datas = (ArrayList<CRMLibraryListData>) msg.obj;
                        if (pageIndex == 1) {
                            crmLibraryListDatas.clear();
                        }
                        if (datas.size() > 0) {
                            mLvList.setVisibility(View.VISIBLE);
                            mLlNoData.setVisibility(View.GONE);

                            crmLibraryListDatas.addAll(datas);
                            mAdapter.bindData(crmLibraryListDatas);

                        }
                        if (crmLibraryListDatas.size() == 0) {
                            mLvList.setVisibility(View.GONE);
                            mLlNoData.setVisibility(View.VISIBLE);
                        }
                        currentCount = datas.size();
                        mHeaderLayout.setVisibility(View.GONE);
                        setFooterText(false);
                        mRefreshableView.onCompleteRefresh();

                    } else {
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case MSG_GET_CHANCE_LIST:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0) {
                        ArrayList<CRMLibraryListData> datas = (ArrayList<CRMLibraryListData>) msg.obj;
                        if (pageIndex == 1) {
                            crmLibraryListDatas.clear();
                        }
                        if (datas.size() > 0) {
                            mLvList.setVisibility(View.VISIBLE);
                            mLlNoData.setVisibility(View.GONE);

                            crmLibraryListDatas.addAll(datas);
                            mChanceAdapter.bindData(crmLibraryListDatas);

                        }
                        if (crmLibraryListDatas.size() == 0) {
                            mLvList.setVisibility(View.GONE);
                            mLlNoData.setVisibility(View.VISIBLE);
                        }
                        currentCount = datas.size();
                        setFooterText(false);
                        mHeaderLayout.setVisibility(View.GONE);
                        mRefreshableView.onCompleteRefresh();

                    } else {
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case MSG_GET_PUBLIC_DEL:
                    if (msg.arg1 == 0) {
                        if (crmLibraryListDatas.size() > mPosition) {
                            crmLibraryListDatas.remove(mPosition);
                        }
                        if (mAdapter != null) {
                            mAdapter.bindData(crmLibraryListDatas);
                        }
                        Toast.makeText(mActivity, "删除成功", Toast.LENGTH_SHORT).show();
                    } else {

                        Toast.makeText(mActivity, (String) msg.obj,
                                Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.crm_library_layout);
        getData();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_ll_back:
                finish();
                break;
            case R.id.title_iv_right:
                Intent create = new Intent(this, CRMCreateEditActivity.class);
                create.putExtra("group_id", mGroupId);
                create.putExtra("type", type);
                if (type == Constants.CRM_PUBLIC_CLUE || type == Constants.CRM_PRIVATE_CLUE) {
                    create.putExtra("action_type", 1);
                } else if (type == Constants.CRM_CHANCE) {
                    create.putExtra("action_type", 4);
                } else if (type == Constants.CRM_CLIENT) {
                    create.putExtra("action_type", 6);
                }
                startActivity(create);
                break;
            case R.id.title_iv_right_left:
                Intent intent = new Intent(CRMLibraryActivity.this, CRMListSearchActivity.class);
                intent.putExtra("group_id", mGroupId);
                intent.putExtra("type", type);
                startActivity(intent);
                break;
            case R.id.rl_library_order_by:
                if (mLvOrderBy.getVisibility() == View.VISIBLE) {
                    mLvOrderBy.setVisibility(View.GONE);
                    mTvOrderBy.setTextColor(getResources().getColor(R.color.schedule_content));
                    Drawable drawable = getResources().getDrawable(R.drawable.crm_order_icon);
                    // 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    mTvOrderBy.setCompoundDrawables(drawable, null, null, null);
                    mIvOrderBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_down));
                } else {
                    mLvOrderBy.setVisibility(View.VISIBLE);
                    mTvOrderBy.setTextColor(getResources().getColor(R.color.crm_select_tab_blue_text));
                    Drawable drawable = getResources().getDrawable(R.drawable.crm_order_selected_icon);
                    // 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    mTvOrderBy.setCompoundDrawables(drawable, null, null, null);
                    mIvOrderBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_up));

                    mLlFilter.setVisibility(View.GONE);
                    mTvFilterBy.setTextColor(getResources().getColor(R.color.schedule_content));
                    Drawable drawable1 = getResources().getDrawable(R.drawable.crm_filter_icon);
                    // 这一步必须要做,否则不会显示.
                    drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                    mTvFilterBy.setCompoundDrawables(drawable1, null, null, null);
                    mIvFilterBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_down));

                }
                updateSelectedFilter(true);
                break;
            case R.id.rl_library_filter_by:
                if (mLlFilter.getVisibility() == View.VISIBLE) {
                    mLlFilter.setVisibility(View.GONE);
                    mTvFilterBy.setTextColor(getResources().getColor(R.color.schedule_content));
                    Drawable drawable = getResources().getDrawable(R.drawable.crm_filter_icon);
                    // 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    mTvFilterBy.setCompoundDrawables(drawable, null, null, null);
                    mIvFilterBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_down));
                    updateSelectedFilter(true);
                } else {
                    mLlFilter.setVisibility(View.VISIBLE);
                    mTvFilterBy.setTextColor(getResources().getColor(R.color.crm_select_tab_blue_text));
                    Drawable drawable = getResources().getDrawable(R.drawable.crm_filter_selected_icon);
                    // 这一步必须要做,否则不会显示.
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    mTvFilterBy.setCompoundDrawables(drawable, null, null, null);
                    mIvFilterBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_up));

                    mLvOrderBy.setVisibility(View.GONE);
                    mTvOrderBy.setTextColor(getResources().getColor(R.color.schedule_content));
                    Drawable drawable1 = getResources().getDrawable(R.drawable.crm_order_icon);
                    // 这一步必须要做,否则不会显示.
                    drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                    mTvOrderBy.setCompoundDrawables(drawable1, null, null, null);
                    mIvOrderBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_down));
                    updateSelectedFilter(false);
                }

                break;
            case R.id.tv_library_filter_by_clear:
                for (CRMFilterFirstData firstData : firstDatas) {
                    firstData.setState(0);
                    for (int i = 0; i < firstData.getSecondDatas().size(); i++) {
                        if (i == 0) {
                            firstData.getSecondDatas().get(i).setState(1);
                        } else {
                            firstData.getSecondDatas().get(i).setState(0);
                        }
                    }
                }
                if (type == Constants.CRM_PUBLIC_CLUE) {
                    mPreferenceUtil.save("crm_public_filter_data", true);
                } else if (type == Constants.CRM_PRIVATE_CLUE) {
                    mPreferenceUtil.save("crm_private_filter_data", true);
                } else if (type == Constants.CRM_CHANCE) {
                    mPreferenceUtil.save("crm_chance_filter_data", true);
                } else if (type == Constants.CRM_CHANCE) {
                    mPreferenceUtil.save("crm_client_filter_data", true);
                }
                updateFilterData();


                break;
            case R.id.tv_library_filter_by_ok:
                //删除数据库内数据,并将当前所有数据,包括选择状态存入到数据库中,更新列表
                Drawable drawable = getResources().getDrawable(R.drawable.crm_order_icon);
                // 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                mLlFilter.setVisibility(View.GONE);
                mTvFilterBy.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvFilterBy.setCompoundDrawables(drawable, null, null, null);
                mIvFilterBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_down));
                updateSelectedFilter(true);
                currentCount = 0;
                pageIndex = 1;
                if (type == Constants.CRM_PUBLIC_CLUE) {
                    getPublicList();
                } else if (type == Constants.CRM_PRIVATE_CLUE) {

                } else if (type == Constants.CRM_CHANCE) {
                    getChanceList();
                } else if (type == Constants.CRM_CLIENT) {

                }
                if (type == Constants.CRM_PUBLIC_CLUE) {
                    mPreferenceUtil.save("crm_public_filter_data", false);
                } else if (type == Constants.CRM_PRIVATE_CLUE) {
                    mPreferenceUtil.save("crm_private_filter_data", false);
                } else if (type == Constants.CRM_CHANCE) {
                    mPreferenceUtil.save("crm_chance_filter_data", false);
                } else if (type == Constants.CRM_CLIENT) {
                    mPreferenceUtil.save("crm_client_filter_data", false);
                }
                mCloudDBOperation.deleteAllCRMClueFilter(type);
                for (int i = 0; i < firstDatas.size(); i++) {
                    ArrayList<CRMFilterSecondData> secondData = firstDatas.get(i).getSecondDatas();
                    for (int j = 0; j < secondData.size(); j++) {
                        mCloudDBOperation.insertCRMClueFilter(type, i + "", firstDatas.get(i).getName(), firstDatas.get(i).getState(), secondData.get(j));
                    }
                }
                break;
            case R.id.view_filter_lv_bottom:
                Drawable drawable1 = getResources().getDrawable(R.drawable.crm_order_icon);
                // 这一步必须要做,否则不会显示.
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                mLlFilter.setVisibility(View.GONE);
                mTvFilterBy.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvFilterBy.setCompoundDrawables(drawable1, null, null, null);
                mIvFilterBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_down));
                updateSelectedFilter(true);
                break;
        }
    }

    @Override
    public void initListener() {
        mLlBack.setOnClickListener(this);
        mIvRight.setOnClickListener(this);
        mIvRightLeft.setOnClickListener(this);
        mRlOrderBy.setOnClickListener(this);
        mRlFilterBy.setOnClickListener(this);
        mTvFilterClear.setOnClickListener(this);
        mTvFilterOk.setOnClickListener(this);
        mFilterBottom.setOnClickListener(this);

        // mLlFilter.setOnTouchListener(this);
        mLvOrderBy.setOnTouchListener(this);

        mLvFirstFilter.setOnItemClickListener(this);
        mLvSecondFilter.setOnItemClickListener(this);
        mLvOrderBy.setOnItemClickListener(this);
        mLvList.setOnItemClickListener(this);
        mLvList.setOnItemLongClickListener(this);

        mLvList.setOnScrollListener(this);
        mRefreshableView.setRefreshableHelper(new RefreshableHelper() {

            @Override
            public View onInitRefreshHeaderView() {
                return LayoutInflater.from(CRMLibraryActivity.this).inflate(R.layout.xlistview_footer, null);
            }

            @Override
            public boolean onInitRefreshHeight(int originRefreshHeight) {
                mRefreshableView.setRefreshNormalHeight(0);
                mRefreshableView.setRefreshingHeight(mRefreshableView.getOriginRefreshHeight());
                mRefreshableView.setRefreshArrivedStateHeight(mRefreshableView.getOriginRefreshHeight());
                return false;
            }

            @Override
            public void onRefreshStateChanged(View refreshView, int refreshState) {
                TextView tv = (TextView) refreshView.findViewById(R.id.xlistview_footer_hint_textview);
                switch (refreshState) {
                    case RefreshableView.STATE_REFRESH_NORMAL:
                        tv.setText("");
                        break;
                    case RefreshableView.STATE_REFRESH_NOT_ARRIVED:
                        tv.setText("正在刷新");
                        break;
                    case RefreshableView.STATE_REFRESH_ARRIVED:
                        tv.setText("正在刷新");
                        break;
                    case RefreshableView.STATE_REFRESHING:
                        tv.setText("正在刷新");
                        pageIndex = 1;
                        if (type == Constants.CRM_PUBLIC_CLUE) {
                            getPublicList();
                        } else if (type == Constants.CRM_PRIVATE_CLUE) {

                        } else if (type == Constants.CRM_CHANCE) {
                            getChanceList();
                        } else if (type == Constants.CRM_CLIENT) {

                        }
                        break;

                }
            }
        });


    }

    @Override
    public void initData() {
        mGroupId = Constants.GROUP_ID;
        Intent intent = getIntent();
        type = intent.getIntExtra("type", 0);
        if (type == Constants.CRM_PUBLIC_CLUE) {
            mTvTitle.setText("公海库");
            mTvOrderBy.setText("创建时间");
        } else if (type == Constants.CRM_PRIVATE_CLUE) {
            mTvTitle.setText("销售线索");
            mTvOrderBy.setText("创建时间");
        } else if (type == Constants.CRM_CHANCE) {
            mTvTitle.setText("销售机会");
            mTvOrderBy.setText("销售阶段");
        } else if (type == Constants.CRM_CLIENT) {
            mTvTitle.setText("销售客户");
            mTvOrderBy.setText("最新创建");
            mIvRightLeft.setVisibility(View.VISIBLE);
        }
        mTvRight.setVisibility(View.GONE);
        mIvRight.setVisibility(View.VISIBLE);
        mIvRight.setImageDrawable(getResources().getDrawable(R.drawable.schedule_add_iv));
        View footerView = LayoutInflater.from(mActivity).inflate(R.layout.xlistview_footer, null);
        mFooterLayout = (LinearLayout) footerView.findViewById(R.id.xlistview_footer_content);
        mFooterText = (TextView) footerView.findViewById(R.id.xlistview_footer_hint_textview);
        mFooterProgress = (ProgressBar) footerView.findViewById(R.id.xlistview_footer_progressbar);
        mFooterLayout.setVisibility(View.GONE);
        mLvList.addFooterView(footerView);
        View headerView = LayoutInflater.from(mActivity).inflate(R.layout.xlistview_footer, null);
        mHeaderLayout = (LinearLayout) headerView.findViewById(R.id.xlistview_footer_content);
        mHeaderText = (TextView) headerView.findViewById(R.id.xlistview_footer_hint_textview);
        mHeaderProgress = (ProgressBar) headerView.findViewById(R.id.xlistview_footer_progressbar);
        mHeaderLayout.setVisibility(View.GONE);
        mHeaderText.setText("正在刷新");
        mLvList.addHeaderView(headerView);


        mFilterFirstAdapter = new CRMFilterAdapter(this);
        mFilterSecondAdapter = new CRMFilterAdapter(this);
        mOrderAdapter = new CRMOrderAdapter(this);
        mAdapter = new CRMLibraryListAdapter(this);
        mChanceAdapter = new CRMChanceListAdapter(this);
        mClientAdapter = new CRMClientListAdapter(this);
        mLvFirstFilter.setAdapter(mFilterFirstAdapter);
        mLvSecondFilter.setAdapter(mFilterSecondAdapter);
        mLvOrderBy.setAdapter(mOrderAdapter);
        if (type == Constants.CRM_PUBLIC_CLUE || type == Constants.CRM_PRIVATE_CLUE) {
            mLvList.setAdapter(mAdapter);
        } else if (type == Constants.CRM_CHANCE) {
            mLvList.setAdapter(mChanceAdapter);
        } else if (type == Constants.CRM_CLIENT) {
            mLvList.setAdapter(mClientAdapter);
        }


        mCloudDBOperation = new CloudDBOperation(this);
        mDialogUtil = AllDialogUtil.getInstance(mActivity);
        mCRMOrderFilterSource = new CRMOrderFilterSource();

    }


    private void getData() {
        httpReqDlgShow();
        if (type == Constants.CRM_PUBLIC_CLUE) {
            boolean isFirst = mPreferenceUtil.getBoolean("crm_public_filter_data", true);
            if (isFirst) {
                firstDatas.addAll(mCRMOrderFilterSource.getPublicClueFilterData(0));
            } else {
                firstDatas = mCloudDBOperation.findCRMClueFilter(type);
                updateSelectedFilter(true);
            }

            ArrayList<Object> filterDatas = new ArrayList<Object>();
            filterDatas.addAll(firstDatas);
            mFilterFirstAdapter.bindData(0, filterDatas);
            ArrayList<Object> secondDatas = new ArrayList<Object>();
            secondDatas.addAll(firstDatas.get(0).getSecondDatas());
            mFilterSecondAdapter.bindData(1, secondDatas);

            ArrayList<CRMOrderByData> orderByDatas = mCRMOrderFilterSource.getPublicClueOrderData();
            mOrderAdapter.bindData(orderByDatas);
            getPublicList();

        } else if (type == Constants.CRM_PRIVATE_CLUE) {//销售线索
            boolean isFirst = mPreferenceUtil.getBoolean("crm_private_filter_data", true);
            if (isFirst) {
                firstDatas.addAll(mCRMOrderFilterSource.getPublicClueFilterData(1));
            } else {
                firstDatas = mCloudDBOperation.findCRMClueFilter(type);
                updateSelectedFilter(true);
            }

            ArrayList<Object> filterDatas = new ArrayList<Object>();
            filterDatas.addAll(firstDatas);
            mFilterFirstAdapter.bindData(0, filterDatas);
            ArrayList<Object> secondDatas = new ArrayList<Object>();
            secondDatas.addAll(firstDatas.get(0).getSecondDatas());
            mFilterSecondAdapter.bindData(1, secondDatas);

            ArrayList<CRMOrderByData> orderByDatas = mCRMOrderFilterSource.getPublicClueOrderData();
            mOrderAdapter.bindData(orderByDatas);
            //getPublicList();
        } else if (type == Constants.CRM_CHANCE) {//机会
            boolean isFirst = mPreferenceUtil.getBoolean("crm_chance_filter_data", true);
            if (isFirst) {
                firstDatas.addAll(mCRMOrderFilterSource.getChanceFilterData());
            } else {
                firstDatas = mCloudDBOperation.findCRMClueFilter(type);
                updateSelectedFilter(true);
            }

            ArrayList<Object> filterDatas = new ArrayList<Object>();
            filterDatas.addAll(firstDatas);
            mFilterFirstAdapter.bindData(0, filterDatas);
            ArrayList<Object> secondDatas = new ArrayList<Object>();
            secondDatas.addAll(firstDatas.get(0).getSecondDatas());
            mFilterSecondAdapter.bindData(1, secondDatas);
            ArrayList<CRMOrderByData> orderByDatas = mCRMOrderFilterSource.getChanceOrderData();
            mOrderAdapter.bindData(orderByDatas);
            getChanceList();
        } else if (type == Constants.CRM_CLIENT) {
            boolean isFirst = mPreferenceUtil.getBoolean("crm_client_filter_data", true);
            if (isFirst) {
                firstDatas.addAll(mCRMOrderFilterSource.getClientFilterData());
            } else {
                firstDatas = mCloudDBOperation.findCRMClueFilter(type);
                updateSelectedFilter(true);
            }

            ArrayList<Object> filterDatas = new ArrayList<Object>();
            filterDatas.addAll(firstDatas);
            mFilterFirstAdapter.bindData(0, filterDatas);
            ArrayList<Object> secondDatas = new ArrayList<Object>();
            secondDatas.addAll(firstDatas.get(0).getSecondDatas());
            mFilterSecondAdapter.bindData(1, secondDatas);
            ArrayList<CRMOrderByData> orderByDatas = mCRMOrderFilterSource.getClientOrderData();
            mOrderAdapter.bindData(orderByDatas);
            // getChanceList();
        }


    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Drawable drawable = getResources().getDrawable(R.drawable.crm_order_icon);
        // 这一步必须要做,否则不会显示.
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        switch (v.getId()) {
            /*case R.id.ll_library_filter:
                mLlFilter.setVisibility(View.GONE);
                mTvFilterBy.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvFilterBy.setCompoundDrawables(drawable, null, null, null);
                mIvFilterBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_down));
                updateSelectedFilter(true);
                break;*/
            case R.id.lv_library_order_by_list:
                mLvOrderBy.setVisibility(View.GONE);
                mTvOrderBy.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvOrderBy.setCompoundDrawables(drawable, null, null, null);
                mIvOrderBy.setImageDrawable(getResources().getDrawable(R.drawable.crm_triangle_down));

                break;
        }
        return false;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.lv_library_filter_first:
                mFilterFirstAdapter.setSelectedPosition(position);
                mFilterFirstAdapter.notifyDataSetChanged();
                mFirstSelectedPosition = position;
                ArrayList<Object> datas = new ArrayList<Object>();
                datas.addAll(firstDatas.get(position).getSecondDatas());
                mFilterSecondAdapter.bindData(1, datas);
                break;
            case R.id.lv_library_filter_second:
                if (position == 0) {//不限--"不限"设置为选中状态,清除其他所有选项
                    firstDatas.get(mFirstSelectedPosition).setState(0);
                    firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(0).setState(1);
                    for (int i = 1; i < firstDatas.get(mFirstSelectedPosition).getSecondDatas().size(); i++) {
                        firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(i).setState(0);
                    }
                    updateFilterData();
                } else {
                    if (((CRMFilterSecondData) mFilterSecondAdapter.getItem(position)).getType() == 1) {//多选
                        if (((CRMFilterSecondData) mFilterSecondAdapter.getItem(position)).getState() == 0) {//没被选中
                            firstDatas.get(mFirstSelectedPosition).setState(1);
                            firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(position).setState(1);//设置为选中状态
                            firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(0).setState(0);
                        } else {// 已经被选中,
                            firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(position).setState(0);
                            boolean flag = false;//看是否有选中的项
                            for (int i = 1; i < firstDatas.get(mFirstSelectedPosition).getSecondDatas().size(); i++) {
                                if (firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(i).getState() == 1) {//如果存在被选中的
                                    flag = true;
                                }
                            }
                            if (!flag) {
                                firstDatas.get(mFirstSelectedPosition).setState(0);
                                firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(0).setState(1);
                            }
                        }
                        updateFilterData();
                    } else {
                        if (((CRMFilterSecondData) mFilterSecondAdapter.getItem(position)).getState() == 0) {//单选未被选中
                            firstDatas.get(mFirstSelectedPosition).setState(1);
                            for (int i = 1; i < firstDatas.get(mFirstSelectedPosition).getSecondDatas().size(); i++) {
                                firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(i).setState(0);
                            }
                            firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(position).setState(1);//设置为选中状态
                            firstDatas.get(mFirstSelectedPosition).getSecondDatas().get(0).setState(0);// "不限"设置为未选中状态
                            updateFilterData();
                        } else {//单选已被选中,不需要操作

                        }
                    }


                }
                break;
            case R.id.lv_library_order_by_list:
                sort = position;
                String name = mOrderAdapter.getItem(position).getName();
                mTvOrderBy.setText(name);
                mOrderAdapter.setSelectedPosition(position);
                if (type == Constants.CRM_PUBLIC_CLUE) {
                    getPublicList();
                } else if (type == Constants.CRM_PRIVATE_CLUE) {

                } else if (type == Constants.CRM_CHANCE) {
                    getChanceList();
                } else if (type == Constants.CRM_CLIENT) {

                }

                break;
            case R.id.lv_library_list:
                if (type == Constants.CRM_PUBLIC_CLUE || type == Constants.CRM_PRIVATE_CLUE) {
                    if (position == mAdapter.getCount() + 1 || position == 0) {
                        return;
                    } else {
                        Intent intent = new Intent(CRMLibraryActivity.this, CRMContactActivity.class);
                        intent.putExtra("clue_id", crmLibraryListDatas.get(position - 1).get_id());
                        intent.putExtra("group_id", mGroupId);
                        intent.putExtra("type", type);
                        startActivity(intent);
                    }
                } else if (type == Constants.CRM_CHANCE) {
                    if (position == mChanceAdapter.getCount() + 1 || position == 0) {
                        return;
                    } else {
                        Intent intent = new Intent(CRMLibraryActivity.this, CRMContactActivity.class);
                        intent.putExtra("clue_id", crmLibraryListDatas.get(position - 1).get_id());
                        intent.putExtra("group_id", mGroupId);
                        intent.putExtra("type", type);
                        startActivity(intent);
                    }
                } else if (type == Constants.CRM_CLIENT) {
                    if (position == mClientAdapter.getCount() + 1 || position == 0) {
                        return;
                    } else {
                        Intent intent = new Intent(CRMLibraryActivity.this, CRMContactActivity.class);
                        intent.putExtra("clue_id", crmLibraryListDatas.get(position - 1).get_id());
                        intent.putExtra("group_id", mGroupId);
                        intent.putExtra("type", type);
                        startActivity(intent);
                    }
                }

                break;
        }
    }

    private void updateFilterData() {
        ArrayList<Object> firsts = new ArrayList<Object>();
        firsts.addAll(firstDatas);
        mFilterFirstAdapter.bindData(0, firsts);

        ArrayList<Object> seconds = new ArrayList<Object>();
        seconds.addAll(firstDatas.get(mFirstSelectedPosition).getSecondDatas());
        mFilterSecondAdapter.bindData(1, seconds);

        updateSelectedFilter(false);

    }

    /**
     * @param filterGone 筛选框是否隐藏,true:隐藏  false:显示
     */
    private void updateSelectedFilter(boolean filterGone) {

        boolean flag = false;
        mLlFilterMsg.removeAllViews();
        for (int i = 0; i < firstDatas.size(); i++) {
            CRMFilterFirstData firstData = firstDatas.get(i);
            StringBuilder sb = new StringBuilder();
            if (firstData.getState() == 1) {
                flag = true;
                for (int j = 1; j < firstDatas.get(i).getSecondDatas().size(); j++) {
                    final CRMFilterSecondData secondData = firstDatas.get(i).getSecondDatas().get(j);
                    if (secondData.getState() == 1) {
                        if (type == Constants.CRM_CHANCE && i == 1) {
                            sb.append(j).append(",");
                        } else if ((type == Constants.CRM_PUBLIC_CLUE || type == Constants.CRM_PRIVATE_CLUE) && i == 0) {
                            if ("其他".equals(secondData.getName())) {
                                sb.append(0).append(",");
                            } else {
                                sb.append(j).append(",");
                            }
                        } else {
                            sb.append(j - 1).append(",");
                        }
                        final View view = LayoutInflater.from(CRMLibraryActivity.this).inflate(R.layout.crm_tab_hl_item, mLlFilterMsg, false);
                        TextView mTvFirst = (TextView) view.findViewById(R.id.tv_crm_tab_hl_item_first);
                        TextView mTvSecond = (TextView) view.findViewById(R.id.tv_crm_tab_hl_item_second);
                        mTvFirst.setText(firstData.getName());
                        mTvSecond.setText(secondData.getName());
                        if (filterGone) {
                            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.crm_gray_corner_bg));
                            mTvFirst.setTextColor(getResources().getColor(R.color.crm_tab_gray_text));
                            mTvSecond.setTextColor(getResources().getColor(R.color.crm_tab_gray_text1));
                        } else {
                            final int finalI = i;
                            final int finalJ = j;
                            view.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mLlFilterMsg.removeView(view);
                                    if (secondData.getType() == 1) {//多选
                                        firstDatas.get(finalI).getSecondDatas().get(finalJ).setState(0);
                                        boolean flag = false;//看是否有选中的项
                                        for (int k = 1; k < firstDatas.get(finalI).getSecondDatas().size(); k++) {
                                            if (firstDatas.get(finalI).getSecondDatas().get(k).getState() == 1) {//如果存在被选中的
                                                flag = true;
                                            }
                                        }
                                        if (!flag) {
                                            firstDatas.get(finalI).setState(0);
                                            firstDatas.get(finalI).getSecondDatas().get(0).setState(1);
                                        }
                                    } else {
                                        firstDatas.get(finalI).setState(0);
                                        firstDatas.get(finalI).getSecondDatas().get(finalJ).setState(0);
                                        firstDatas.get(finalI).getSecondDatas().get(0).setState(1);
                                    }
                                    ArrayList<Object> firsts = new ArrayList<Object>();
                                    firsts.addAll(firstDatas);
                                    mFilterFirstAdapter.bindData(0, firsts);

                                    ArrayList<Object> seconds = new ArrayList<Object>();
                                    seconds.addAll(firstDatas.get(mFirstSelectedPosition).getSecondDatas());
                                    mFilterSecondAdapter.bindData(1, seconds);
                                    if (mLlFilterMsg.getChildCount() == 0) {
                                        mHsvFilter.setVisibility(View.GONE);
                                        vHsvLine.setVisibility(View.GONE);
                                    }
                                }
                            });
                        }

                        mLlFilterMsg.addView(view);

                    }
                }

                if (type == Constants.CRM_PUBLIC_CLUE || type == Constants.CRM_PRIVATE_CLUE) {
                    switch (i) {
                        case 0:
                            mOrigin = sb.substring(0, sb.length() - 1);
                            break;
                        case 1:
                            mStatus = sb.substring(0, sb.length() - 1);
                            break;
                        case 2:
                            mActiveTime = sb.substring(0, sb.length() - 1);
                            break;
                        case 3:
                            mUpdateTime = sb.substring(0, sb.length() - 1);
                            break;
                        case 4:
                            mCreateTime = sb.substring(0, sb.length() - 1);
                            break;
                    }

                } else if (type == Constants.CRM_CHANCE) {
                    switch (i) {
                        case 0:
                            mMarketAmount = sb.substring(0, sb.length() - 1);
                            if ("-1".equals(mMarketAmount)) {
                                mMarketAmount = "-1";
                            } else if ("0".equals(mMarketAmount)) {
                                mMarketAmount = "1000";
                            } else if ("1".equals(mMarketAmount)) {
                                mMarketAmount = "10000";
                            } else if ("2".equals(mMarketAmount)) {
                                mMarketAmount = "100000";
                            } else if ("3".equals(mMarketAmount)) {
                                mMarketAmount = "1000000";
                            } else if ("4".equals(mMarketAmount)) {
                                mMarketAmount = "10000000";
                            }
                            break;
                        case 1:
                            mMarketStage = sb.substring(0, sb.length() - 1);
                            break;
                        case 2:
                            mStatementDate = sb.substring(0, sb.length() - 1);
                            break;
                    }

                } else if (type == Constants.CRM_CLIENT) {

                }

            }
        }

        if (flag) {

            mHsvFilter.setVisibility(View.VISIBLE);
            vHsvLine.setVisibility(View.VISIBLE);
        } else {
            mOrigin = "-1";
            mStatus = "-1";
            mActiveTime = "-1";
            mUpdateTime = "-1";
            mCreateTime = "-1";
            mMarketAmount = "-1";
            mMarketStage = "-1";
            mStatementDate = "-1";
            mHsvFilter.setVisibility(View.GONE);
            vHsvLine.setVisibility(View.GONE);

        }
    }

    /**
     *
     */
    private void getPublicList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ORIGIN, mOrigin));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STATUS, mStatus));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ACTIVE_TIME, mActiveTime));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_UPDATE_TIME, mUpdateTime));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CREATE_TIME, mCreateTime));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SORT, sort + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, "10"));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, pageIndex + ""));

        CRMLibraryListMsg msg = new CRMLibraryListMsg(mHandler.obtainMessage(MSG_GET_PUBLIC_LIST));
        msg.mApi = AsynHttpClient.API_CRM_PUBLIC_LIST;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCRMHttp(msg);

    }

    /**
     * 销售机会列表
     */
    private void getChanceList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MARKET_STAGE, mMarketStage));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MARKET_AMOUNT, mMarketAmount));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STATEMENT_DATE, mStatementDate));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SORT, sort + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, "10"));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, pageIndex + ""));

        CRMChanceListMsg msg = new CRMChanceListMsg(mHandler.obtainMessage(MSG_GET_CHANCE_LIST));
        msg.mApi = AsynHttpClient.API_CRM_CHANCE_LIST;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCRMHttp(msg);

    }


    private void delPublicMsg(String id) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CLUE_ID, id));

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_GET_PUBLIC_DEL));
        msg.mApi = AsynHttpClient.API_CRM_PUBLIC_DEL;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCRMHttp(msg);

    }


    public void showDelPublicDlg(final String id) {
        String okText = this.getString(R.string.label_btn_ok);
        String cancelText = this.getString(R.string.cancel);
        mDialogUtil.titleDeleteMsgStyle("删除公海线索", okText, cancelText, "删除此条公海线索");

        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                delPublicMsg(id);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();

            }

        });

    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (view.getId()) {
            case R.id.lv_library_list:
                if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
                    if (is_scrolling) {
                        if (currentCount < pageSize) {
                            setFooterText(false);
                        } else {
                            // TODO 直接从接口读取数据，不先读取数据库
                            ++pageIndex;
                            if (type == Constants.CRM_PUBLIC_CLUE) {
                                getPublicList();
                            } else if (type == Constants.CRM_PRIVATE_CLUE) {

                            } else if (type == Constants.CRM_CHANCE) {
                                getChanceList();
                            } else if (type == Constants.CRM_CLIENT) {

                            }
                        }


                    } else {
                        // 判断滚动到顶部
                        if (mLvList.getFirstVisiblePosition() == 0) {
                            //mLvList.setHeaderDividersEnabled(false);
                            mHeaderLayout.setVisibility(View.VISIBLE);
                            pageIndex = 1;
                            if (type == Constants.CRM_PUBLIC_CLUE ) {
                                getPublicList();
                            }else if (type == Constants.CRM_PRIVATE_CLUE) {

                            } else if (type == Constants.CRM_CHANCE) {
                                getChanceList();
                            } else if (type == Constants.CRM_CLIENT) {

                            }
                        }
                    }


                }
                break;
        }

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        switch (view.getId()) {
            case R.id.lv_library_list:
                if ((firstVisibleItem + visibleItemCount == totalItemCount) && totalItemCount != 0 && firstVisibleItem != 0) {
                    if (currentCount < pageSize) {
                        setFooterText(false);
                    } else {
                        setFooterText(true);
                    }
                    is_scrolling = true;
                } else {
                    is_scrolling = false;
                }
                break;
        }

    }

    public void setFooterText(boolean isShow) {
        if (isShow) {
            mFooterLayout.setVisibility(View.VISIBLE);
            mFooterText.setText(this.getResources().getString(R.string.xlistview_footer_hint_normal));
            mFooterProgress.setVisibility(View.VISIBLE);
        } else {
            mFooterLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (type == Constants.CRM_PUBLIC_CLUE) {//管理员可以进入公海库，删除公海中的线索。
            mPosition = position - 1;
            showDelPublicDlg(((CRMLibraryListData) mAdapter.getItem(position - 1)).get_id());
            return true;
        }

        return true;
    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = mDialogUtil.waitDialog();
//            mProgressDialog.setCancelable(false);
            if (!mWaitDialog.isShowing()) {
                mWaitDialog.show();
            }
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }
}




